import { defineStore } from 'pinia'
import { ref } from 'vue'

export const user = defineStore('id', () => {

    const token = ref(localStorage.getItem('token') || "");

    const user: any = ref({
        id: (Math.random()),
        uname: "还未登录",
        phone: "暂未绑定",
        money: 0,
        levels: 0,
        bookshelf: "",
        msg: "",
        concern: "",
        fans: 0,
        readTime: 0,
        lastTime: "",
        touImg: "",
        sex: "",
        birth: "",
        address: "",

    })
    const getLevels = () => {
        let arr = [20, 150, 400, 1000, 2000, 5000, 10000, 20000, 50000]
        let value = 0
        arr.some((item: number) => {
            if (item > user.value.levels) {
                value = item - user.value.levels
                return true;
            }
        })
        return value;
    }
    const changeToken = (a: any) => {
        token.value = a
        localStorage.setItem('token', a)
    }
    const changeUser = (obj: any) => {
        for (let i in obj) {
            if (user.value[i] === undefined) {
                continue;
            } else if (obj[i] === '') {
                user.value[i] = ''
            } else {
                user.value[i] = obj[i]
            }
        }
    }
    const exit = () => {
        token.value = ""
        user.value = {
            id: (Math.random()),
            uname: "还未登录",
            phone: "暂未绑定",
            money: 0,
            levels: 0,
            bookshelf: "",
            msg: "",
            concern: "",
            fans: 0,
            readTime: 0,
            lastTime: "",
            touImg: "",
            sex: "",
            birth: "",
            address: "",
        }
    }
    const sendMoney = (money: any) => {
        user.value.money = money
    }
    const addLevels = (num: number) => {
        user.value.levels = num
    }

    const ispos = ref(0)
    const ispositon = (num:any) => {
        ispos.value= num
    }

    return {
        token,
        user,
        changeToken,
        changeUser,
        exit,
        sendMoney,
        getLevels,
        addLevels,
        ispos,
        ispositon
    }
})